﻿using System;
using System.Threading.Tasks;
using Devonline.Core;
using Devonline.Entity;
using Devonline.Http;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;
using Microsoft.Extensions.Logging;
using ProjectManagement.Models;

namespace ProjectManagement.Controllers
{
    [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
    public class IssuesController : ODataController
    {
        private readonly ApplicationDbContext _context;
        private readonly ILogger<IssuesController> _logger;

        public IssuesController(ApplicationDbContext context, ILogger<IssuesController> logger)
        {
            _context = context;
            _logger = logger;
        }

        [EnableQuery]
        public IActionResult Get()
        {
            return Ok(_context.Issues);
        }

        public async Task<IActionResult> Post([FromBody] Issue entitySet)
        {
            if (entitySet == null)
            {
                throw new Exception($"{typeof(Issue).GetDisplayName()} 不能为空!");
            }

            await _context.UniqueAsync<Issue, string>(entitySet);
            entitySet.Create();
            entitySet.Update();

            ////处理附加信息, 无附加信息则不用写下面的代码及删除文件的代码
            //_context.AddAdditionals<Issue, Additional, string>(entitySet, entitySet.Additionals);

            ////处理附件, 无附件则不用写下面的代码及删除文件的代码
            //_context.AddAttachments<Issue, Attachment, string>(entitySet, entitySet.Attachments);

            _context.Add(entitySet);
            await _context.SaveChangesAsync().ConfigureAwait(true);
            return Ok(entitySet);
        }

        public async Task<IActionResult> Put(string key, [FromBody] Issue entitySet)
        {
            var displayName = typeof(Issue).GetDisplayName();
            if (entitySet == null)
            {
                throw new Exception($"{displayName} 不能为空!");
            }

            var entity = await _context.Issues.FindAsync(key);
            if (entity == null)
            {
                throw new Exception($"{displayName} 中当前记录不存在!");
            }

            await _context.UniqueAsync<Issue, string>(entitySet);
            entitySet.CopyTo(entity);
            entity.Update();

            //处理附加信息, 无附加信息则不用写下面的代码及删除文件的代码
            await _context.UpdateAdditionalsAsync<Issue, Additional, string>(entity, entity.Additionals);

            //处理附件, 无附件则不用写下面的代码及删除文件的代码
            var files = await _context.UpdateAttachmentsAsync<Issue, Attachment, string>(entitySet, entitySet.Attachments, nameof(Issue));

            _context.Update(entity);
            await _context.SaveChangesAsync().ConfigureAwait(true);
            files.Delete(_logger);
            return Ok();
        }

        public async Task<IActionResult> Delete(string key)
        {
            var displayName = typeof(Issue).GetDisplayName();
            var entitySet = await _context.Issues.FindAsync(key);
            if (entitySet == null)
            {
                throw new Exception($"{typeof(Issue).GetDisplayName()} 中当前记录不存在!");
            }

            //处理附加信息, 无附加信息则不用写下面的代码及删除文件的代码
            //var additionals = await _context.GetQueryable<Additional>().Where(x => x.BusinessKey == entitySet.Id).ToListAsync();
            //if (additionals.IsNotNullOrEmpty())
            //{
            //    _context.RemoveRange(additionals);
            //}

            //处理附件, 无附件则不用写下面的代码及删除文件的代码
            var files = await _context.DeleteAttachmentsAsync<Attachment, string>(entitySet.Id);

            _context.Remove(entitySet);
            await _context.SaveChangesAsync().ConfigureAwait(true);
            files.Delete(_logger);
            return Ok();
        }
    }
}
